package handler

import (
	"encoding/json"
	newssql "gitee.com/bingshiwuyu/backend-platform/mysql"
	"gitee.com/bingshiwuyu/trace-source/model"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"github.com/wonderivan/logger"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

// Response ...
type Response struct {
	Code    int32       `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// dbCommon db公共部分
func dbCommon(dbName, tableName string, condition interface{}, value ...interface{}) *gorm.DB {
	return newssql.Get(dbName).Master().Table(tableName).Where(condition, value...)
}

//ParsePostRequestParams 解析参数
func ParsePostRequestParams(r *http.Request, param interface{}) {
	body, _ := ioutil.ReadAll(r.Body)
	if body == nil || strings.EqualFold(string(body), "") {
		return
	}

	err := json.Unmarshal(body, param)
	if err != nil {
		logger.Error("ParsePostRequestParams|PostParams:error%v", err)
		return
	}
}

func createInfo(req model.TraceSourceRecord) (int, error) {
	record := &model.TraceSourceRecord{
		Name:     req.Name,
		Project:  req.Project,
		Creator:  req.Creator,
		Location: req.Location,
		Time:     time.Now().Format("2006-01-02 15:04:05"),
	}
	r := newssql.Get("trace").Master().Table("tracesource").Create(record)
	if r.Error != nil {
		logger.Error("AddApkDB", "err", r.Error.Error(), record)
		return 0, r.Error
	}
	logger.Info("AddApkDB:#%v", record.Location)
	return record.ID, nil
}
func UpdateHandler(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			c.JSON(http.StatusOK, gin.H{"error": 499, "msg": "keystore upload abnormal"})
			return
		}
	}()
	req := model.TraceSourceRecord{}
	ParsePostRequestParams(c.Request, &req)

	userid, err := createInfo(req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": 499, "data": 0, "msg": "数据错误"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"error": 200, "data": userid, "msg": "创建成功"})
	return
}

func TraceGetHandler(c *gin.Context) {
	id := c.Query("uid")
	logger.Debug("id:%v", id)
	record := &model.TraceSourceRecord{}
	r := dbCommon("trace", "tracesource", "id = ?", id).Find(&record)

	if r.Error != nil {
		c.JSON(http.StatusOK, gin.H{"error": 499, "data": 0, "msg": "数据不存在"})
		return
	}
	to, _ := time.Parse("2006-01-02T15:04:05Z", record.Time)
	record.Time = to.Format("2006-01-02 15:04:05")
	c.JSON(http.StatusOK, gin.H{"error": 200, "data": record, "msg": "获取成功"})
	return
}

//func PictureUploadHandler(c *gin.Context) {
//	defer func() {
//		if err := recover(); err != nil {
//			log.Debug("PictureUploadHandler recover panic err:%v", err)
//			c.JSON(http.StatusOK, gin.H{"error": model.ERROR_CODE_CLIENT_ERROR, "msg": "fileupload abnormal"})
//			return
//		}
//	}()
//
//	begin := time.Now().Unix()
//	req, fileHeader, err := c.Request.FormFile("file")
//	if err != nil {
//		c.JSON(http.StatusOK, gin.H{"error": model.ERROR_CODE_CLIENT_ERROR, "msg": "fileupload abnormal"})
//		return
//	}
//	log.Debugf("filename:%v, fileHeader:%v", fileHeader.Filename, fileHeader.Header)
//
//	filename := "./" + fileHeader.Filename
//	file, err := os.Create(filename)
//	if err != nil {
//		c.JSON(http.StatusOK, gin.H{"error": model.ERROR_CODE_SERVER_ERROR, "msg": "fileupload abnormal"})
//		return
//	}
//	_, err = io.Copy(file, req)
//	if err != nil {
//		c.JSON(http.StatusOK, gin.H{"error": model.ERROR_CODE_SERVER_ERROR, "msg": "fileupload abnormal"})
//		return
//	}
//
//	mid := time.Now().Unix()
//	url, err := common.PictureUpload(fileHeader.Filename)
//	if err != nil {
//		c.JSON(http.StatusOK, gin.H{"error": model.ERROR_CODE_SERVER_ERROR, "msg": "fileupload abnormal"})
//		return
//	}
//	end := time.Now().Unix()
//	log.Infof("total time begin:%v, mid:%v, end:%v, diff:%v", begin, mid, end, end-begin)
//
//	c.JSON(http.StatusOK, gin.H{"error": model.ERROR_CODE_SUCCESS, "msg": "", "data": url})
//	return
//}
//
//func VerfifyUploadHandler(c *gin.Context) {
//	defer func() {
//		if err := recover(); err != nil {
//			log.Debug("PictureUploadHandler recover panic err:%v", err)
//			c.JSON(http.StatusOK, gin.H{"error": model.ERROR_CODE_SERVER_ERROR, "msg": "fileupload abnormal"})
//			return
//		}
//	}()
//
//	userData := model.User{}
//	model.ParsePostRequestParams(c.Request, &userData)
//
//	log.Debugf("url:%v", userData)
//	record, err := dao.GetKeyStroy(userData.App, userData.Username)
//	if err != nil {
//		c.JSON(http.StatusOK, gin.H{"error": model.ERROR_CODE_SERVER_ERROR, "msg": err.Error()})
//		return
//	}
//
//	rsa, err := newsrsa.NewXRsa()
//	if err != nil {
//		log.Errorf("NewXRsa:%v", err)
//		c.JSON(http.StatusOK, gin.H{"error": model.ERROR_CODE_SERVER_ERROR, "msg": "rsa err"})
//		return
//	}
//
//	pri, _ := rsa.PrivateDecrypt(record.Sign)
//
//	log.Debugf("rsa:%v", pri)
//	c.JSON(http.StatusOK, gin.H{"error": model.ERROR_CODE_SUCCESS, "msg": "keystore upload succ"})
//}
